<template>
  <div class="role-management" v-loading="loading">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增角色</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="请输入角色名称或描述"
        clearable
        style="width: 300px; margin-left: 16px"
        @keyup.enter="handleSearch" />
      <el-button type="primary" @click="handleSearch" style="margin-left: 8px">搜索</el-button>
    </div>

    <el-table :data="roleList" style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleToggleStatus(row)">
            {{ row.status === 1 ? "禁用" : "启用" }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      @current-change="handlePageChange" />

    <!-- 角色表单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="权限配置" prop="permissions">
          <el-row>
            <el-col
              :span="12"
              v-for="(label, key) in permissionOptions"
              :key="key"
              style="margin-bottom: 8px; display: flex; align-items: center">
              <el-switch
                v-model="permissionSwitches[key]"
                :active-value="true"
                :inactive-value="false"
                @change="updatePermissionsJson" />
              <span style="margin-left: 12px">{{ label }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="roleForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { http } from "@/api";

// 表格数据
const roleList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索关键词
const searchKeyword = ref("");

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增角色");
const isEdit = ref(false);
const roleFormRef = ref(null);

const roleForm = reactive({
  id: null,
  name: "",
  description: "",
  permissions: "",
  status: 1,
});

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 50, message: "角色名称长度在 2 到 50 个字符", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
  permissions: [
    { required: true, message: "请输入权限配置", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value) {
          try {
            JSON.parse(value);
            callback();
          } catch (e) {
            callback(new Error("权限配置必须是有效的JSON格式"));
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 权限选项
const permissionOptions = {
  user: "用户管理",
  supplier: "供应商管理",
  purchaser: "采购商管理",
  role: "角色管理",
};
// 权限 Switch 状态
const permissionSwitches = reactive({
  user: false,
  supplier: false,
  purchaser: false,
  role: false,
});
// 权限 Switch 状态变化时，更新 roleForm.permissions
function updatePermissionsJson() {
  roleForm.permissions = JSON.stringify(permissionSwitches, null, 2);
}
// 新增/编辑时初始化权限 Switch
function setPermissionSwitchesFromJson(jsonStr) {
  let obj = {};
  try {
    obj = JSON.parse(jsonStr);
  } catch (e) {}
  for (const key in permissionSwitches) {
    permissionSwitches[key] = !!obj[key];
  }
}

// 获取角色数据
const fetchRoleList = async (page = 1) => {
  loading.value = true;
  try {
    const params = {
      page: page,
      size: pageSize.value,
    };
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim();
    }
    const res = await http.get("/api/roles", params);
    console.log("角色数据:", res.data);
    roleList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error("获取角色列表失败");
    console.error("获取角色列表失败:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchRoleList(currentPage.value);
});

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchRoleList(page);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRoleList(1);
};

// 处理新增角色
const handleAdd = () => {
  dialogTitle.value = "新增角色";
  isEdit.value = false;
  Object.assign(roleForm, {
    id: null,
    name: "",
    description: "",
    permissions: JSON.stringify(
      {
        user: false,
        supplier: false,
        purchaser: false,
        role: false,
      },
      null,
      2
    ),
    status: 1,
  });
  setPermissionSwitchesFromJson(roleForm.permissions);
  dialogVisible.value = true;
};

// 处理编辑角色
const handleEdit = (row) => {
  dialogTitle.value = "编辑角色";
  isEdit.value = true;
  let permissions = "{}";
  if (row.permissions) {
    try {
      const parsed = JSON.parse(row.permissions);
      permissions = JSON.stringify(parsed, null, 2);
    } catch (e) {
      permissions = row.permissions;
    }
  }
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    description: row.description || "",
    permissions: permissions,
    status: row.status,
  });
  setPermissionSwitchesFromJson(roleForm.permissions);
  dialogVisible.value = true;
};

// 处理删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该角色吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.delete(`/api/roles/${row.id}`);
      ElMessage.success("删除成功");
      fetchRoleList(currentPage.value);
    } catch (error) {
      ElMessage.error("删除失败");
      console.error("删除角色失败:", error);
    }
  });
};

// 处理启用/禁用状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? "启用" : "禁用";

  ElMessageBox.confirm(`确定要${statusText}该角色吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.patch(`/api/roles/${row.id}/status?status=${newStatus}`);
      ElMessage.success(`${statusText}成功`);
      fetchRoleList(currentPage.value);
    } catch (error) {
      ElMessage.error("状态更新失败");
      console.error("更新角色状态失败:", error);
    }
  });
};

// 处理表单提交
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate();
    submitLoading.value = true;

    // 验证权限配置JSON格式
    let permissions = roleForm.permissions;
    try {
      JSON.parse(permissions);
    } catch (e) {
      ElMessage.error("权限配置必须是有效的JSON格式");
      return;
    }

    if (isEdit.value) {
      await http.put(`/api/roles/${roleForm.id}`, roleForm);
      ElMessage.success("更新成功");
    } else {
      await http.post("/api/roles", roleForm);
      ElMessage.success("添加成功");
    }

    dialogVisible.value = false;
    fetchRoleList(currentPage.value);
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error("提交失败");
    }
    console.error("提交角色数据失败:", error);
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style scoped>
.role-management {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-help {
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.permission-help p {
  margin: 0 0 4px 0;
  font-weight: bold;
}

.permission-help pre {
  margin: 0;
  font-family: "Courier New", monospace;
  background-color: #fff;
  padding: 4px;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
}
</style>
